package com.qiusuo0226.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiusuo0226.common.constant.NumConstant;
import com.qiusuo0226.common.util.AlgorithmTool;
import com.qiusuo0226.mvc.util.JsonResultModel;
import com.qiusuo0226.core.mapper.DictionaryMapper;
import com.qiusuo0226.core.pojo.dto.DictionaryAddDTO;
import com.qiusuo0226.core.pojo.entity.DictionaryDO;
import com.qiusuo0226.core.pojo.vo.DictionaryGroupPageVO;
import com.qiusuo0226.core.service.DictionaryService;
import com.qiusuo0226.mysql.property.MybatisPlusProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 字典 逻辑层 实现
 * @author qiusuo
 * @date 2023/7/23 21:44
 */
@Service
@Slf4j
public class DictionaryServiceimpl extends ServiceImpl<DictionaryMapper, DictionaryDO> implements DictionaryService {

    @Autowired
    private MybatisPlusProperty mybatisPlusProperty;

    @Override
    public JsonResultModel add(DictionaryAddDTO dto) {

        // 根据字典组编码查看字典组是否存在
        QueryWrapper<DictionaryDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_code", dto.getGroupCode());
        List<DictionaryDO> dictionaryDOS = baseMapper.selectList(queryWrapper);
        DictionaryDO dictionaryDO = null;
        if (null != dictionaryDOS && !dictionaryDOS.isEmpty()) {
            // 当新增类型是1，则代表字典组整体新增，此时字典组编码理应在库中不存在，若存在则返回新增失败
            if (StringUtils.equals(dto.getType(), NumConstant.S1)) {
                return JsonResultModel.failure(NumConstant.S30001, "该字典组编码已存在");
            } else {
                dictionaryDO = dictionaryDOS.get(0);
                dto.setGroupName(dictionaryDO.getGroupName());
                dto.setGroupCode(dictionaryDO.getGroupCode());
            }
        }
        StringBuffer buffer = new StringBuffer();
        dictionaryDOS.forEach(item -> {
            buffer.append(item.getDictionaryCode());
            buffer.append(",");
        });

        List<DictionaryAddDTO.Dictionary> dictionaries = dto.getDictionaries();
        List<DictionaryDO> entitys = new ArrayList<>();
        Date date = new Date();
        try {
            for (int i = 0, len = dictionaries.size(); i < len; i++) {
                DictionaryAddDTO.Dictionary item = dictionaries.get(i);
                // 如果字符串中已经包含该字典值的code
                if (buffer.toString().contains(item.getDictionaryCode())) {
                    throw new Exception("字典值的编码【" + item.getDictionaryCode() + "】已存在");
                }
                DictionaryDO entity = new DictionaryDO();
                entity.setIid(AlgorithmTool.snowflake(mybatisPlusProperty.getGlobalConfig().datacenterId, mybatisPlusProperty.getGlobalConfig().workerId));
                entity.setGmtCreate(date);
                entity.setGmtModify(date);
                entity.setDeleted("0");
                entity.setVersion(1);
                entity.setGroupName(dto.getGroupName());
                entity.setGroupCode(dto.getGroupCode());
                entity.setDictionaryName(item.getDictionaryName());
                entity.setDictionaryCode(item.getDictionaryCode());
                entity.setSort(item.getSort());
                entitys.add(entity);
            }
        } catch (Exception e) {
            JsonResultModel failure = JsonResultModel.failure(NumConstant.S30002, e.getMessage());
            return failure;
        }


        int i = baseMapper.insertBatch(entitys);
        return i > NumConstant.N0 ? JsonResultModel.success("新增成功") : JsonResultModel.failure("新增失败");
    }

    @Override
    public JsonResultModel list(String groupCode, String searchWord) {
        QueryWrapper<DictionaryDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("iid,group_name groupName,group_code groupCode,dictionary_name dictionaryName,dictionary_code dictionaryCode,sort");
        queryWrapper.eq("group_code", groupCode);
        queryWrapper.like(StringUtils.isNotBlank(searchWord), "dictionary_name", searchWord);
        queryWrapper.orderByAsc("sort");
        List<Map<String, Object>> dictionaryDOS = baseMapper.selectMaps(queryWrapper);
        dictionaryDOS.forEach((item) -> {
            item.put("iid", String.valueOf(MapUtils.getLong(item, "iid", null)));
        });
        return JsonResultModel.success(dictionaryDOS);
    }

    @Override
    public JsonResultModel groupList(String searchWord, Integer pageNo, Integer pageSize) {
        Page<DictionaryDO> page = new Page(pageNo, pageSize);
        IPage<Map<String, Object>> iPage = baseMapper.groupList(page, searchWord);

        // 分页结果组装
        DictionaryGroupPageVO pageVO = new DictionaryGroupPageVO();
        pageVO.setPageNo(iPage.getCurrent());
        pageVO.setPageSize(iPage.getSize());
        pageVO.setTotal(iPage.getTotal());
        pageVO.setList(iPage.getRecords());
        return JsonResultModel.success(pageVO);
    }

    @Override
    public JsonResultModel editGroup(String groupName, String groupCode) {
        int effectRows = baseMapper.editGroup(groupName, groupCode);
        return effectRows > 0 ? JsonResultModel.success("编辑成功") : JsonResultModel.failure("编辑失败");
    }

    @Override
    public JsonResultModel edit(String iid, String dictionaryName, String dictionaryCode, Integer sort) {
        int effectRows = baseMapper.edit(iid, dictionaryName, dictionaryCode, sort);
        return effectRows > 0 ? JsonResultModel.success("编辑成功") : JsonResultModel.failure("编辑失败");
    }

    @Override
    public JsonResultModel removeGroup(String groupCode) {
        int effectRows = baseMapper.removeGroup(groupCode);
        return effectRows > 0 ? JsonResultModel.success("删除成功") : JsonResultModel.failure("删除失败");
    }

    @Override
    public JsonResultModel remove(String groupCode, String dictionaryCodes) {
        String[] dictionaryCodeArrays = dictionaryCodes.split(",");
        int effectRows = baseMapper.remove(groupCode, dictionaryCodeArrays);
        return effectRows > 0 ? JsonResultModel.success("删除成功") : JsonResultModel.failure("删除失败");
    }
}
